import { Module } from 'vuex'
import { CartState, RootState } from '../types'
import { CartService } from '@/api/cart'

const cartModule: Module<CartState, RootState> = {
  namespaced: true,
  
  state: {
    items: [],
    loading: false
  },
  
  mutations: {
    SET_CART_ITEMS(state, items) {
      state.items = items
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    }
  },
  
  actions: {
    async getCartItems({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await CartService.getCartItems()
        commit('SET_CART_ITEMS', response.data)
        return response.data
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async addToCart({ dispatch }, { productId, quantity }) {
      await CartService.addToCart(productId, quantity)
      return dispatch('getCartItems')
    },
    
    async updateCartItem({ dispatch }, { id, quantity }) {
      await CartService.updateCartItem(id, quantity)
      return dispatch('getCartItems')
    },
    
    async removeCartItem({ dispatch }, itemId) {
      await CartService.removeCartItem(itemId)
      return dispatch('getCartItems')
    }
  }
}

export default cartModule 